<template>
  <div class="offset-curve-container">
    <div class="scroll-wrapper">
      <div class="curve-container" ref="curveContainerRef">
        <svg ref="svgRef" class="offset-curve-svg" :width="svgWidth" :height="height" @click="clearSelected">
          <!-- 坐标轴 -->
          <g class="coordinate-system">
            <!-- Y轴 -->
            <line x1="40" y1="20" x2="40" :y2="height - 30" class="axis" />
            <!-- X轴 -->
            <line x1="40" :y1="height - 30" :x2="svgWidth - 20" :y2="height - 30" class="axis" />
            
            <!-- Y轴刻度和标签 -->
            <g class="y-axis-labels">
              <template v-for="i in 7" :key="`y-label-${i}`">
                <line
                  x1="35"
                  :y1="20 + (i - 1) * ((height - 50) / 6)"
                  x2="40"
                  :y2="20 + (i - 1) * ((height - 50) / 6)"
                  class="tick"
                />
                <text
                  x="30"
                  :y="20 + (i - 1) * ((height - 50) / 6)"
                  class="axis-label"
                  text-anchor="end"
                  dominant-baseline="middle"
                >
                  {{ 300 - (i - 1) * 100 }}
                </text>
              </template>
              <!-- Y轴标题 -->
              <text
                x="10"
                :y="height / 2"
                class="axis-title"
                text-anchor="middle"
                transform="rotate(-90, 10, height / 2)"
              >
                
              </text>
            </g>
          </g>

          <!-- 网格线 -->
          <g class="grid-lines">
            <template v-for="i in 20" :key="`x-${i}`">
              <line
                :x1="getXPosition(i)"
                y1="20"
                :x2="getXPosition(i)"
                :y2="height - 30"
                class="grid-line"
              />
            </template>
            <template v-for="i in 6" :key="`y-${i}`">
              <line
                x1="40"
                :y1="20 + i * ((height - 50) / 6)"
                :x2="svgWidth - 20"
                :y2="20 + i * ((height - 50) / 6)"
                class="grid-line"
              />
            </template>
          </g>

          <!-- 中心线 -->
          <line
            x1="40"
            :y1="height / 2"
            :x2="svgWidth - 20"
            :y2="height / 2"
            class="center-line"
          />

          <!-- 桩桶标记和编号 -->
          <g class="cone-markers">
            <template v-for="i in 20" :key="`cone-${i}`">
              <circle
                :cx="getXPosition(i)"
                :cy="height / 2"
                r="4"
                class="cone-marker"
              />
              <text
                :x="getXPosition(i)"
                :y="height - 10"
                class="cone-number"
                text-anchor="middle"
              >
                {{ i }}
              </text>
            </template>
          </g>

          <!-- 偏移曲线 -->
          <path
            :d="curvePath"
            class="offset-curve"
            fill="none"
          />

          <!-- 偏移点（hover 在点旁显示标签框） -->
          <g class="offset-points">
            <g v-for="point in offsetPoints" :key="point.id" class="offset-point-group" :class="{ active: selectedPointId === point.id }" @click.stop="selectPoint(point.id)">
              <circle
                :cx="point.x"
                :cy="point.y"
                r="4"
                class="offset-point"
              />
              <!-- 背景框 -->
              <rect
                class="offset-label-bg"
                :x="point.x + 6"
                :y="point.y - (getLabelHeight()) - 6"
                :width="getLabelWidth(point)"
                :height="getLabelHeight()"
                rx="6" ry="6"
                :style="{ opacity: (selectedPointId === point.id) ? 1 : 0 }"
              />
              <!-- 文本 -->
              <text
                class="offset-label"
                :x="point.x + 6 + labelPaddingX"
                :y="point.y - getLabelHeight() + labelLineHeight"
                :style="{ opacity: (selectedPointId === point.id) ? 1 : 0 }"
              >
                第<tspan class="offset-number">{{ point.id }}</tspan>桩
                <tspan
                  :x="point.x + 6 + labelPaddingX"
                  :dy="labelLineHeight"
                >
                  偏移: <tspan class="offset-number">{{ point.offsetValue }}</tspan>mm  {{ point.direction === 'l' ? '左绕' : point.direction === 'r' ? '右绕' : '直行' }}
                </tspan>
              </text>
            </g>
          </g>
        </svg>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'

const props = defineProps({
  width: {
    type: Number,
    default: 1000
  },
  height: {
    type: Number,
    default: 200
  },
  offsetData: {
    type: Object,
    default: () => ({})
  }
})

// SVG引用
const svgRef = ref(null)
const curveContainerRef = ref(null)

// 计算SVG宽度，确保每个桩桶有足够空间
const minConeWidth = 80 // 每个桩桶的最小宽度
const svgWidth = computed(() => Math.max(props.width, minConeWidth * 20 + 60))

// 获取X坐标位置
function getXPosition(index) {
  const totalWidth = svgWidth.value - 60 // 减去左右边距
  const xScale = totalWidth / 20
  return (index - 0.5) * xScale + 40
}

// 偏移点数据处理
const offsetPoints = ref([])
const curvePath = ref('')
const selectedPointId = ref(null)
const labelPaddingX = 8
const labelLineHeight = 14

// 标签内容与宽度估算（用于背景框）
function getPointLabel(point) {
  const dir = point.direction === 'l' ? '左绕' : point.direction === 'r' ? '右绕' : '直行'
  return `第${point.id}桩  ${point.offsetValue}mm  ${dir}`
}

function getLabelWidth(point) {
  // 两行宽度取最大：第一行 "第NN桩"，第二行 "偏移: XXXmm 方向"
  const line1 = `第${point.id}桩`
  const dir = point.direction === 'l' ? '左绕' : point.direction === 'r' ? '右绕' : '直行'
  const line2 = `偏移: ${point.offsetValue}mm  ${dir}`
  const approxCharWidth = 8
  const horizontalPadding = labelPaddingX * 2
  const w1 = line1.length * approxCharWidth + horizontalPadding
  const w2 = line2.length * approxCharWidth + horizontalPadding
  return Math.max(w1, w2)
}

function getLabelHeight() {
  // 上下内边距 + 两行文字高度
  const verticalPadding = 8
  return verticalPadding * 2 + labelLineHeight * 2
}

function selectPoint(id) {
  selectedPointId.value = id
}

function clearSelected() {
  selectedPointId.value = null
}

// 计算偏移点和曲线
function calculateOffsetPoints() {
  const points = []
  const scale = (props.height - 50) / 600 // 300mm上下偏移，总高度600mm

  for (let i = 1; i <= 20; i++) {
    const idStr = i.toString().padStart(3, '0')
    const direction = props.offsetData[`${idStr}dir`] || 'n'
    const value = parseInt(props.offsetData[`${idStr}val`] || '0', 10)

    const x = getXPosition(i)
    let y = props.height / 2

    if (direction === 'l') {
      y -= value * scale
    } else if (direction === 'r') {
      y += value * scale
    }

    points.push({
      id: i,
      x,
      y,
      direction,
      offsetValue: value
    })
  }

  offsetPoints.value = points
  calculateCurvePath(points)
}

// 计算曲线路径
function calculateCurvePath(points) {
  if (points.length < 2) return ''

  let path = `M ${points[0].x} ${points[0].y}`
  
  for (let i = 0; i < points.length - 1; i++) {
    const current = points[i]
    const next = points[i + 1]
    const cp1x = current.x + (next.x - current.x) / 3
    const cp2x = current.x + 2 * (next.x - current.x) / 3
    
    path += ` C ${cp1x},${current.y} ${cp2x},${next.y} ${next.x},${next.y}`
  }

  curvePath.value = path
}

// 监听偏移数据变化
watch(() => props.offsetData, () => {
  calculateOffsetPoints()
}, { deep: true })

// 组件挂载时初始化
onMounted(() => {
  calculateOffsetPoints()
})
</script>

<style scoped>
.offset-curve-container {
  position: relative;
  width: 100%;
  background: white;
  border-radius: 8px;
  padding: 20px 30px 40px 50px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.scroll-wrapper {
  width: 100%;
  overflow-x: auto;
  overflow-y: hidden;
  -webkit-overflow-scrolling: touch;
}

.curve-container {
  min-width: 100%;
  position: relative;
}

.offset-curve-svg {
  display: block;
  min-width: 100%;
}

.grid-line {
  stroke: #f0f0f0;
  stroke-width: 1;
}

.center-line {
  stroke: #e0e0e0;
  stroke-width: 2;
  stroke-dasharray: 5,5;
}

.cone-marker {
  fill: #909399;
  stroke: white;
  stroke-width: 1;
}

.offset-curve {
  stroke: #409EFF;
  stroke-width: 2;
  stroke-linecap: round;
  stroke-linejoin: round;
  filter: drop-shadow(0 2px 4px rgba(64, 158, 255, 0.2));
}

.offset-point {
  fill: #409EFF;
  stroke: white;
  stroke-width: 1;
  cursor: pointer;
  transition: r 0.2s;
}

.offset-point:hover {
  r: 5;
}

.axis {
  stroke: #303133;
  stroke-width: 2;
}

.tick {
  stroke: #303133;
  stroke-width: 1;
}

.axis-label {
  font-size: 12px;
  fill: #606266;
}

.axis-title {
  font-size: 14px;
  fill: #303133;
  font-weight: 500;
}

.cone-number {
  font-size: 12px;
  fill: #606266;
  font-weight: 500;
}

.offset-label {
  opacity: 0;
  transition: opacity 0.15s ease;
  font-size: 12px;
  fill: #303133;
  paint-order: stroke;
  stroke: #ffffff;
  stroke-width: 2px;
}

.offset-number {
  fill: #409EFF;
  stroke: none;
}

.offset-label-bg {
  fill: rgba(0,0,0,0.7);
  stroke: rgba(255,255,255,0.9);
  stroke-width: 1px;
  opacity: 0;
  transition: opacity 0.15s ease;
}

.offset-point-group:hover .offset-label,
.offset-point-group:hover .offset-label-bg,
.offset-point-group.active .offset-label,
.offset-point-group.active .offset-label-bg {
  opacity: 1;
}

/* 自定义滚动条样式 */
.scroll-wrapper::-webkit-scrollbar {
  height: 8px;
}

.scroll-wrapper::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.scroll-wrapper::-webkit-scrollbar-thumb {
  background: #409EFF;
  border-radius: 4px;
}

.scroll-wrapper::-webkit-scrollbar-thumb:hover {
  background: #337ecc;
}

/* 暗色主题样式 */
[data-theme="dark"] .offset-curve-container {
  background: var(--card-bg);
  border: 1px solid var(--border-color);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
}

[data-theme="dark"] .grid-line {
  stroke: var(--border-color);
  opacity: 0.3;
}

[data-theme="dark"] .center-line {
  stroke: var(--text-secondary);
  opacity: 0.5;
}

[data-theme="dark"] .cone-marker {
  fill: var(--text-secondary);
  stroke: var(--card-bg);
}

[data-theme="dark"] .offset-curve {
  stroke: var(--neon-blue);
  filter: drop-shadow(0 0 8px var(--neon-blue));
}

[data-theme="dark"] .offset-point {
  fill: var(--neon-blue);
  stroke: var(--card-bg);
}

[data-theme="dark"] .offset-point:hover {
  filter: drop-shadow(0 0 6px var(--neon-blue));
}

[data-theme="dark"] .axis {
  stroke: var(--text-primary);
}

[data-theme="dark"] .tick {
  stroke: var(--text-primary);
}

[data-theme="dark"] .axis-label {
  fill: var(--text-secondary);
  font-family: 'LED16Segment', monospace;
}

[data-theme="dark"] .axis-title {
  fill: var(--text-primary);
}

[data-theme="dark"] .cone-number {
  fill: var(--text-secondary);
  font-family: 'LED16Segment', monospace;
}

[data-theme="dark"] .offset-label {
  fill: var(--text-primary);
  stroke: rgba(0, 0, 0, 0.8);
}

[data-theme="dark"] .offset-label-bg {
  fill: rgba(0,0,0,0.85);
  stroke: var(--neon-blue);
}

[data-theme="dark"] .offset-number {
  fill: var(--neon-blue);
}

[data-theme="dark"] .scroll-wrapper::-webkit-scrollbar-track {
  background: var(--border-color);
}

[data-theme="dark"] .scroll-wrapper::-webkit-scrollbar-thumb {
  background: var(--neon-blue);
  box-shadow: 0 0 4px var(--neon-blue);
}

[data-theme="dark"] .scroll-wrapper::-webkit-scrollbar-thumb:hover {
  background: var(--neon-cyan);
  box-shadow: 0 0 6px var(--neon-cyan);
}
</style>
